import * as React from 'react';
import {ColorResult, ChromePicker} from 'react-color';

import AbsSimpleAttrRenderer from './AbsSimpleAttrRenderer';

export interface ColorAttrRendererState {
  isColorPickerShown: boolean;
  selectedColor: string;
}

class ColorAttrRenderer extends AbsSimpleAttrRenderer<ColorAttrRendererState> {

  constructor(props) {
    super(props);

    this.state = {
      isColorPickerShown: false,
      selectedColor: ''
    };
  }

  protected renderContent() {
    const {attribute} = this.props;
    const attrVal: any = this.getAttrVal();

    return (
      <div className="Attribute-item-content-group">
        <input name={attribute.name} value={attrVal} onChange={this.changeHandler} placeholder={attribute.placeholder}/>
        <div className="Attribute-color-picker-btn input-add-on" onClick={this.showColorPicker}>
          <div style={{backgroundColor: attrVal}}/>
        </div>
        {this.renderColorPicker(attrVal)}
      </div>
    );
  }

  private renderColorPicker(attrVal: any) {
    if (this.state.isColorPickerShown) {
      const color = this.state.selectedColor || attrVal;
      return (
        <div className="Attribute-color-picker-popover">
          <div className="Attribute-backdrop" onClick={this.hideColorPicker}/>
          <ChromePicker color={color} onChangeComplete={this.colorChangeHandler}/>
        </div>
      );
    }
  }

  private colorChangeHandler = (color: ColorResult) => {
    this.setState({...this.state, selectedColor: color.hex});
  }

  private showColorPicker = () => {
    this.setState({...this.state, isColorPickerShown: true});
  }

  private hideColorPicker = () => {
    this.setState({...this.state, isColorPickerShown: false});

    if (this.state.selectedColor !== this.getAttrVal()) {
      this.notifyViewChanged(this.state.selectedColor);
    }
  }
}

export default ColorAttrRenderer;
